<?php

class Categorys{
    protected $tree = null;
    protected $store_id;
	/**
	 * $_id 指定要获取的分类ID,将只会获取它本身和它下面的子分类
	 * $store_id 指定要显示哪个版块的分类信息
	 */
	function __construct( $_this, $store_id=1, $_id=0)
	{
		$this->db = $_this->db;
		$this->store_id = $store_id;
		$this->_id = $_id;
	}
	
    /**
     * 获取指定分类子分类Array(cate_id=>array(cate_name, level, ……)
     * 
	 * 用户显示下拉列表分灰的值
	 *
	 * @param unknown_type $level =>　显示至几级分类
	 * @return unknown
	 */
    function get_options($store_id = 1, $level = 0){
    	
		$this->tree = null;
		$this->store_id = $store_id;

        $arr = $this->list_child($level);
        
        $options = array();
        
        foreach ($arr as $val)
        {

             $options[] = array('categoryId' => $val['categoryId'], 'cateName' => str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $val['level']) . '├ ' . $val['cateName']);
             
        }
        
        return $options;        
    }
	
	function get_list($store_id = 1, $level = 0){		
		$this->tree = null;
		$this->store_id = $store_id;
        $arr = $this->list_child($level);        
        $data = array();       
        foreach ($arr as $val){        	
             $data[] = array(
             	'categoryId' => $val['categoryId'], 
             	'parentId' => $val['parentId'],
             	'child'		=> $val['child'],
             	'cateName' => $val['cateName'],
             	'level'	=> $val['level'],
				'isMenu' => $val['isMenu'],
             	'cateSort' => $val['cateSort'],
				'productCount' => $val['productCount'],
				'createdTime' => date('Y-m-d', $val['createdTime'])
             );
        }
		return $data;        
    }
    
    /**
     * 获取所有子分类
     *
     * @param unknown_type $level => 显示至几级分类
     * @return unknown
     */
    function list_child ($level = 0){
    	
        $list = $this->_get_child($level);

        return $list;
        
    }
    /**
     * @param unknown_type $level => 0　是显示所有分类的
     * @param unknown_type $this->_id => 指定只显示某一个分类与其下面的子分类
     * @return unknown
     */
	function _get_child($level){
		
	    if ($this->tree === null){
	    	$this->_init_tree();
	    }

	    if ($level == 0 && empty($this->_id)){
	        return $this->tree;
	    }
	
	    if ($this->_id == 0){
	        $param = array('categoryId' => 0, 'level' => 0, 'dir' => '0');
	    }else{
	    	
	        $param = $this->tree[$this->_id];
	    }
	
	    $param['add_level'] = $level;
	    
	    //按指定的条件过滤掉不要显示的分类
	    category_filter(array(), $param);
	    
	    return  array_filter($this->tree, "category_filter");
	    
	}

   /**
    * 初始化分类数据
    */
	function _init_tree(){

		$arr = $this->db->fetch_all("SELECT categoryId,storeId,cateName,parentId,cateSort,productCount,createdTime,isMenu FROM `god_category` WHERE storeId = '{$this->store_id}'   ");
		
		$count = count($arr);
		$data = array();
		
		for($i=0; $i < $count; $i++){
			
			$data[$arr[$i]['categoryId']] = $arr[$i];
			
		}
		
		//循环统计出每个分类是属于第几级分类
		foreach ($data as $val){
			
			$this->_build($val['categoryId'], $data);
			
		}
		
		//按照定义的category_sort函数时行自定义排序
		category_sort(array(), array(), $data);
		
		uasort($data, "category_sort");
		
		$this->tree = $data;
	
	}

	/**
	 * 计算出当前分类是属于几级分类
	 *
	 * @param unknown_type $cate_id => 分类ID
	 * @param unknown_type $data => 引用同一个 $data 数据做比较
	 */
	function _build($cate_id, &$data){
		
		if (!isset($data[$cate_id]['child'])) {
			
			$data[$cate_id]['child'] = 0;
			
		}
		
		$parents = array();
		$parent_id = $data[$cate_id]['parentId'];

		$level = 1;
		
		while (isset($data[$parent_id]) && (!in_array($parent_id, $parents))){
			
		    if (isset($data[$parent_id]['child'])){
		    	
		        $data[$parent_id]['child'] ++;
		        
		    }else{
		    	
		        $data[$parent_id]['child'] = 1;
		        
		    }
		
		    $parents[] = $parent_id;
		    $level ++;
		    $parent_id = $data[$parent_id]['parentId'];
		    
		}
		
		$parents[] = 0;
		$parents = array_reverse($parents);
		$data[$cate_id]['dir'] = implode('/', $parents);
		$data[$cate_id]['level'] = $level;
	}
	
}


/**
 * 分类排序函数
 */
function category_sort($a, $b, $add_data=null){
	
	static $data = null;
	if (isset($add_data)){
		
	    $data = $add_data;
	    return true;
	    
	}
	
	if ($a['dir'] == $b['dir']){
	
	    if ($a['cateSort'] == $b['cateSort']){
	    	
	        return $a['categoryId'] < $b['categoryId'] ? -1 : 1;
	        
	    }
	    
	    return $a['cateSort'] < $b['cateSort'] ? -1 : 1;
	    
	}else{
	
		//level => 当前分类处在几级分类
	    $count = min($a['level'], $b['level']);
	
	    $tmp_a = explode('/', $a['dir']);
	    $tmp_b = explode('/', $b['dir']);
	
	    for ($i=0; $i< $count; $i++){
	    	
	        if ($tmp_a[$i] != $tmp_b[$i]){
	        	
	            if ($data[$tmp_a[$i]]['cateSort'] == $data[$tmp_b[$i]]['cateSort']){
	            	
	                return $data[$tmp_a[$i]]['categoryId'] < $data[$tmp_b[$i]]['categoryId'] ? -1 : 1;
	                
	            }
	            
	            return $data[$tmp_a[$i]]['cateSort'] < $data[$tmp_b[$i]]['cateSort'] ? -1 : 1;
	            
	        }
	    }
	    
	    if ($a['level'] < $b['level']){
	    	
	        if ($tmp_b[$count] == $a['categoryId']){	        	
	            return -1;
	        }
	        
	        if ($data[$a['categoryId']]['cateSort'] == $data[$tmp_b[$count]]['cateSort']){
	            return  $a['categoryId'] < $tmp_b[$count] ? -1 : 1;
	        }
	        
	        return $data[$a['categoryId']]['cateSort'] < $data[$tmp_b[$count]]['cateSort'] ? -1 : 1;
	        
	    }else{
	    	
	        if ($tmp_a[$count] == $b['categoryId']){	        	
	            return 1;
	        }
	        
	        if ($data[$b['categoryId']]['cateSort'] == $data[$tmp_a[$count]]['cateSort']){
	            return  $tmp_a[$count] < $b['categoryId'] ? -1 : 1;
	        }
	        
	        return $data[$tmp_a[$count]]['cateSort'] < $data[$b['categoryId']]['cateSort'] ? -1 : 1;
	    }
	}
}


/**
 * 分类过滤函数
 */
function category_filter($val, $add_param = null)
{
    static $param = 0;
    if (isset($add_param)){
    	
        $param = $add_param;

        if ($param['categoryId'] > 0){
        	
           $param['parent_dir'] = $param['dir'] . '/' . $param['categoryId'];
           $param['parent_dir_ext'] = $param['dir'] . '/' . $param['categoryId'] . '/';
           
        }else{
        	
            $param['parent_dir'] = '0';
            $param['parent_dir_ext'] = '0/';
            
        }

        //取至几层分类
        $param['last_level'] =  $param['level'] + $param['add_level'];
        $param['parent_dir_ext_length'] = strlen($param['parent_dir_ext']);

        return true;
    }
    
    if ($val['categoryId'] == $param['categoryId']){
        return true;
    }

    if ($val['level'] > $param['level']){
    	
    	//所处分类层次大于指定获取层次的将会返回false
        if ($param['add_level'] > 0 && ($val['level'] > $param['last_level'])){
            return false;
        }
        
        if ($val['dir'] == $param['parent_dir'] ||  strncmp($val['dir'], $param['parent_dir_ext'], $param['parent_dir_ext_length']) == 0){
            return true;
        }
        
        return false;
    }
}

?>